import React from "react";
import ReactDOM from "react-dom";
/* // 实现useState
let lastState;
function useState(initialState) {
  lastState = lastState || initialState;
  function setState(newState) {
    lastState = newState;
    render();
  }
  return [lastState, setState];
} */

// 实现useState, 修复使用多次useState出现的问题
// 通过定义个数组对象，以及stateIndex索引，每次调用useState都把索引增加，可以进行区别不同的useState
let lastStates = [];
let stateIndex = 0;
function useState(initialState) {
  lastStates[stateIndex] = lastStates[stateIndex] || initialState;
  let currentIndex = stateIndex;
  function setState(newState) {
    lastStates[currentIndex] = newState;
    render();
    stateIndex = 0;
  }
  return [lastStates[stateIndex++], setState];
}
function App() {
  // 定义num值为0，并设置一个改变num值的方法setNum
  const [num, setNum] = useState(0);
  return (
    <div>
      <p>{num}</p>
      <button onClick={() => setNum(num + 1)}>+</button>
    </div>
  );
}
function render() {
  ReactDOM.render(<App />, document.getElementById("root"));
}
render();
